package com.hy;

import java.util.*;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:找到字符串中所有字母异位词
 *
 * 输入: s = "cbaebabacd", p = "abc"
 * 输出: [0,6]
 * 解释:
 * 起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。
 * 起始索引等于 6 的子串是 "bac", 它是 "abc" 的异位词。
 * author: Mr.Du
 * Date: 2023/9/23
 * Time: 14:55
 */
public class FindAnagrams {


    public List<Integer> findAnagrams(String s, String p) {
        int[] arr = new int[26];
        int[] win = new int[26];
        List<Integer> res = new ArrayList<>();
        int ls = s.length(), lp = p.length();
        for(int i = 0;i < lp;i++){
            arr[p.charAt(i) - 'a']++;
        }
        int slow = 0, fast = 0;
        while(fast < ls){
            win[s.charAt(fast) - 'a']++;
            if(fast - slow== lp - 1){
                if(Arrays.equals(win, arr)) res.add(slow);
                win[s.charAt(slow) - 'a']--;
                slow++;
            }
            fast++;
        }
        return res;
    }

    public List<Integer> findAnagrams1(String s, String p) {
        int[] win = new int[26];
        List<Integer> res = new ArrayList<>();
        int ls = s.length(), lp = p.length();
        for(int i = 0;i < lp;i++){
            win[p.charAt(i) - 'a']++;
        }
        int slow = 0, fast = 0;
        while(fast < ls){
            int count = fast;
            for(int i = fast;i < fast + lp;i++){
                if(win[s.charAt(i) - 'a'] != 0){
                    win[s.charAt(i) - 'a']--;
                    count++;
                }else{
                    slow = i + 1;
                    fast = i + 1;
                    break;
                }
            }
            if(count == fast + lp) res.add(slow);
            for(int i = fast;i < count;i++){
                win[s.charAt(i) - 'a']++;
            }
        }
        return res;
    }
}
